package com.ysd.lis.service.lab.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.ysd.common.Result;
import com.ysd.common.dto.OrganizationDTO;
import com.ysd.constant.AlphabetArray;
import com.ysd.lis.entity.SysMenu;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.lab.LabProcessSet;
import com.ysd.lis.entity.lab.LabUnqualifiedGroup;
import com.ysd.lis.mapper.lab.LabProcessSetMapper;
import com.ysd.lis.mapper.sys.SysMenuMapper;
import com.ysd.lis.request.ProcessDto;
import com.ysd.lis.service.SysMenuService;
import com.ysd.lis.service.lab.LabProcessSetService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 流程设定主表 服务实现类
 * </p>
 *
 * @author bai
 * @since 2024-02-19
 */
@Service
public class LabProcessSetServiceImpl extends ServiceImpl<LabProcessSetMapper, LabProcessSet> implements LabProcessSetService {

    @Autowired
    LabProcessSetMapper processSetMapper;

    @Autowired
    LabProcessSetService processSetService;
    @Autowired
    SysMenuService sysMenuService;
    @Autowired
    SysMenuMapper sysMenuMapper;

    @Override
    public Result getProcessSetList(LabProcessSet labProcessSet) {
        MPJLambdaWrapper<LabProcessSet> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(LabProcessSet::getDelFlag, 0);
        if (ToolsUtils.isNotEmpty(labProcessSet)) {
            if (ToolsUtils.isNotEmpty(labProcessSet.getKeywords())) {
                queryWrapper.like(LabProcessSet::getNodeName, labProcessSet.getKeywords());
            }
        }

        if (BeanUtil.isNotEmpty(labProcessSet.getIsTat()) && labProcessSet.getIsTat()) {
            queryWrapper.eq(LabProcessSet::getIsTat, 1);
        }

        queryWrapper.orderByAsc(LabProcessSet::getSeq);
        List<LabProcessSet> list = processSetMapper.selectList(queryWrapper);
        return Result.succ(list);
    }

    @Override
    public List<LabProcessSet> findProcessSetList() {
        MPJLambdaWrapper<LabProcessSet> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(LabUnqualifiedGroup::getDelFlag, 0);
        queryWrapper.orderByAsc(LabProcessSet::getSeq);
        List<LabProcessSet> list = processSetMapper.selectList(queryWrapper);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result daleteProcess(ProcessDto deleteParam) {
        List<LabProcessSet> labProcessSetList = deleteParam.getLabProcessSets();

        List<String> ids = labProcessSetList.stream().map(LabProcessSet::getId).collect(Collectors.toList());

        boolean b = this.removeByIds(ids);
        if (b) {
            return Result.succ(1, "删除成功", null);
        } else {
            return Result.fail(400, "删除失败", "");
        }
    }

    //updateProcess
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result updateProcess(ProcessDto processDto) {
        if (ToolsUtils.isEmpty(processDto)) {
            return Result.fail("入参不可为空");
        }
        List<LabProcessSet> labProcessSets = processDto.getLabProcessSets();
        boolean save = this.updateBatchById(labProcessSets);
        if (save) {
            // for (LabProcessSet labProcessSet : labProcessSets) {
            //     LambdaUpdateWrapper<SysMenu> updateWrapper = new LambdaUpdateWrapper<>();
            //     updateWrapper.set(SysMenu::getTitle,labProcessSet.getNodeName());
            //     updateWrapper.set(SysMenu::getUrl,labProcessSet.getNodeUrl()+"?code="+labProcessSet.getCode());
            //     updateWrapper.eq(SysMenu::getCode,labProcessSet.getCode());
            //     boolean updateMenu = sysMenuService.update(updateWrapper);
            //     if(!updateMenu){
            //         return Result.fail("修改菜单失败");
            //     }
            // }
            return Result.fail("修改成功");
        } else {
            return Result.fail("修改失败");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result addProcess(ProcessDto processDto) {
        if (ToolsUtils.isEmpty(processDto)) {
            return Result.fail("入参不可为空");
        }
        List<LabProcessSet> labProcessSets = processDto.getLabProcessSets();
        SysUser sysUser = RedisUserManager.getUser();
        for (LabProcessSet labProcessSet : labProcessSets) {
            labProcessSet.setOrgId(sysUser.getOrgId());
            // labProcessSet.setCode(IncrementalNumberGenerator.generateIncrementalNumber5());
        }
        boolean save = this.saveBatch(labProcessSets);
        if (save) {
            // List<SysMenu> menus = new ArrayList<>();
            // for (LabProcessSet labProcessSet : labProcessSets) { //批量存储到菜单表标本管理模块下，条码管理子菜单中。
            //     SysMenu sysMenu = new SysMenu();
            //     sysMenu.setUrl(labProcessSet.getNodeUrl()+"?code="+labProcessSet.getCode());
            //     sysMenu.setOrgId(sysUser.getOrgId());
            //     sysMenu.setTitle(labProcessSet.getNodeName());
            //     sysMenu.setModuleId("1747828187831173122");
            //     sysMenu.setParentId("1747829779582124034");
            //     sysMenu.setCode(labProcessSet.getCode());
            //     menus.add(sysMenu);
            // }
            // boolean saveSysMenu = sysMenuService.saveBatch(menus);
            // if(saveSysMenu){
            //     return Result.fail("新增成功");
            // }else{
            //     return Result.fail("新增菜单失败");
            // }
            return Result.fail("新增成功");
        } else {
            return Result.fail("新增节点失败");
        }
    }

    @Override
    @Transactional
    public Result addProcessInfo(LabProcessSet processSet) {
        SysUser sysUser = RedisUserManager.getUser();
        if (!StringUtils.isEmpty(processSet.getNodeUrl())) {
            SysMenu sysMenu = new SysMenu();
            sysMenu.setUrl(processSet.getNodeUrl() + "?code=" + processSet.getCode());
            sysMenu.setOrgId(sysUser.getOrgId());
            sysMenu.setTitle(processSet.getNodeName());
            //TODO ID暂时写死,后期从菜单取
            sysMenu.setModuleId("1747828187831173122");
            sysMenu.setParentId("1747829779582124034");
            sysMenu.setCode(processSet.getCode());
            boolean saveSysMenu = sysMenuService.save(sysMenu);
            if (!saveSysMenu) {
                return Result.fail("添加标本流程节点失败");
            }
            processSet.setSysMenuId(sysMenu.getId());
        }
        //processSet.setOrgId(sysUser.getOrgId());
        int i = processSetMapper.insert(processSet);
        if (i > 0) {
            return Result.succ(1, "新建成功", "");
        } else {
            return Result.fail("添加标本流程节点失败");
        }

    }

    @Override
    @Transactional
    public Result updateProcessInfo(LabProcessSet processSet) {
        //判断是否有界面
        if (!StringUtils.isEmpty(processSet.getNodeUrl())) {
            SysMenu sysMenu = new SysMenu();
            SysUser sysUser = RedisUserManager.getUser();
            if (!StringUtils.isEmpty(processSet.getSysMenuId())) {
                sysMenu.setUrl(processSet.getNodeUrl() + "?code=" + processSet.getCode());
                sysMenu.setId(processSet.getSysMenuId());
                sysMenuMapper.updateById(sysMenu);
            } else {
                sysMenu.setUrl(processSet.getNodeUrl() + "?code=" + processSet.getCode());
                sysMenu.setOrgId(processSet.getOrgId());
                sysMenu.setTitle(processSet.getNodeName());
                //TODO ID暂时写死,后期从菜单取
                sysMenu.setModuleId("1747828187831173122");
                sysMenu.setParentId("1747829779582124034");
                sysMenu.setCode(processSet.getCode());
                sysMenuMapper.insert(sysMenu);
                processSet.setSysMenuId(sysMenu.getId());
            }
        } else {
            sysMenuMapper.deleteById(processSet.getSysMenuId());
            processSet.setSysMenuId(null);
        }

        int i = processSetMapper.updateById(processSet);
        if (i > 0) {
            return Result.succ(1, "修改成功", "");
        } else {
            return Result.fail("修改标本流程节点失败");
        }
    }

    @Override
    public Result getNodeListByCode(String code) {
        MPJLambdaWrapper<LabProcessSet> queryWrapper = new MPJLambdaWrapper<>();
        SysUser sysUser = RedisUserManager.getUser();
        if (ToolsUtils.isNotEmpty(sysUser)) {
            queryWrapper.eq(LabProcessSet::getOrgId, sysUser.getOrgId());
        }
        queryWrapper.eq(LabProcessSet::getDelFlag, 0);
        queryWrapper.eq(LabProcessSet::getCode, code);
        List<LabProcessSet> list = processSetMapper.selectList(queryWrapper);
        // List<LabProcessAttribute> list = new ArrayList<>();
        // if (ToolsUtils.isNotEmpty(labProcessSet)) {
        //     String id = labProcessSet.getId();
        //     MPJLambdaWrapper<LabProcessAttribute> queryAttributeWrapper = new MPJLambdaWrapper<>();
        //     queryAttributeWrapper.eq(LabProcessAttribute::getProcessSetId, id);
        //     queryAttributeWrapper.eq(LabProcessAttribute::getDelFlag, 0);
        //     if (ToolsUtils.isNotEmpty(sysUser)) {
        //         queryAttributeWrapper.eq(LabProcessAttribute::getOrgId, sysUser.getOrgId());
        //     }
        //     list = processAttributeMapper.selectList(queryAttributeWrapper);
        // }
        return Result.succ(list);
    }

    @Override
    public Result copyProcessSetData(OrganizationDTO input) {
        String sourceOrgId = input.getSourceOrgId();
        String goalOrgId = input.getGoalOrgId();
        Integer orgIndex = input.getOrgIndex();
        String s = AlphabetArray.Alphabet[orgIndex];


        MPJLambdaWrapper<LabProcessSet> queryWrapper = new MPJLambdaWrapper<>();
        queryWrapper.eq(LabProcessSet::getOrgId, sourceOrgId);
        queryWrapper.eq(LabProcessSet::getDelFlag, 0);
        List<LabProcessSet> list = processSetMapper.selectList(queryWrapper);

        List<LabProcessSet> newList=new ArrayList<>();
        processSetMapper.delete(new LambdaQueryWrapper<LabProcessSet>().eq(LabProcessSet::getOrgId, goalOrgId));
        for (LabProcessSet labProcessSet : list) {
            LabProcessSet copyProcessSet = new LabProcessSet();
            BeanUtil.copyProperties(labProcessSet, copyProcessSet,"id", "orgId");
            String id = labProcessSet.getId();
            String newId = s + id.substring(s.length());
            copyProcessSet.setId(newId);
            copyProcessSet.setOrgId(goalOrgId);
            newList.add(copyProcessSet);
        }
        processSetService.saveBatch(newList);
        return null;
    }
}
